<?php
/**
 * Controller_Admin_Hotel
 *
 * Класс Controller_Admin_Hotel отвечает за обработку гостиниц в админке
 *
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.0
 */
class Controller_Admin_Hotel extends Controller_Admin {

	/**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
		Service_Debug::setDebug();
		switch ($this->arrRequest[2]) {
			case '':
				$this->getIndex();
			  break;
			case 'add':
				$this->actionAdd();
			  break;
			case 'edit':
				$hotelId = intval($this->arrRequest[3]);
				$objHotel = new Hotel($hotelId);
				if ($objHotel->id) $this->actionEdit($objHotel);
				else $this->setError(404);
				break;
			case 'rooms':
				$hotelId = intval($this->arrRequest[3]);
				$objHotel = new Hotel($hotelId);
				if ($objHotel->id) $this->actionRooms($objHotel);
				else $this->setError(404);
				break;
			default:
				$this->setError(404);
				break;
		}
	}

	/**
	 * Выводит список гостиниц для администрирования
	 * 
	 */
	public function getIndex() {
	  Service_Debug::setDebug();
	  $additionalConditions = " 1 ";
	  $canFindHotels = true;
	  if ($_GET) {
	  	$arrSearchParams = Service_Escape::absolutelyEscapeArray($_GET['Hotel']);
      if (!empty($arrSearchParams['country_name'])) { 
      	$countryName = $arrSearchParams['country_name'];
      	$objCountry = new Country();
      	$arrCountries = $objCountry->find('all', array('select' => '`country_code`', 'conditions' => "`country_final_name_ru` LIKE '" . $countryName . "%' OR `country_final_name_en` LIKE '" . $countryName . "%'"));
      	if (!$arrCountries) {
      		$canFindHotels = false;
      		$additionalConditions .= " AND 0";
      	}
      	else {
      		$arrCountryCodes = Service_ArrayConverter::getColumn($arrCountries, 'country_code');
      		$additionalConditions .= " AND `hotel`.`country_code` IN ('" . join("', '", $arrCountryCodes) . "')";
      	}
      }
      if (!empty($arrSearchParams['city_name']) && $canFindHotels) { // Получаем города соответствующие запросу
      	$cityName = $arrSearchParams['city_name'];
      	$objCity = new City();
      	$arrCities = $objCity->find('all', array('select' => '`ID_city`', 'conditions' => "`city_final_name_ru` LIKE '" . $cityName . "%' OR `city_final_name_en` LIKE '" . $cityName . "%' AND " . str_replace('`hotel`.', '`city`.', $additionalConditions)));
        if (!$arrCities) {
      		$canFindHotels = false;
      		$additionalConditions .= " AND 0";
      	}
      	else {
      		$arrCityIds = Service_ArrayConverter::getColumn($arrCities, 'ID_city');
      		$additionalConditions .= " AND `hotel`.`ID_city` IN ('" . join("', '", $arrCityIds) . "')";
      	}
      }
      if (!empty($arrSearchParams['hotel_name']) && $canFindHotels) {
      	$hotelName = $arrSearchParams['hotel_name'];
      	$additionalConditions .= " AND (`hotel_final_name_ru` LIKE '" . $hotelName . "%' OR `hotel_final_name_en` LIKE '" . $hotelName . "%') ";
      }
      if (!empty($arrSearchParams['not_filled']) && $canFindHotels) { 
      	$additionalConditions .= " AND `hotel`.`is_filled` = 0 ";
      } 
	  }
		$objHotel = new Hotel();
	  $arrHotels = $objHotel->find('all', array(
	    'select' => '`hotel`.`hotel_final_name_ru`, `hotel`.`is_filled`, `hotel`.`hotel_url`, `hotel`.`city_url`, `hotel`.`country_url`, `hotel`.`hotel_final_name_en`, `hotel`.`ID_hotel`, `hotel`.`ID_city`, `hotel`.`country_code`, `country`.`country_final_name_ru`, `country`.`country_final_name_en`, `country_admin_name_ru_2`, `country_admin_name_ru_6`, `city`.`city_final_name_ru`, `city`.`city_final_name_en`', 
	    'order' => '`hotel_final_name_ru` ASC, `hotel_final_name_en` ASC',
	    'joins' => 'LEFT JOIN `country` ON `country`.`country_code` = `hotel`.`country_code` LEFT JOIN `city` ON `city`.`ID_city` = `hotel`.`ID_city`',
	    'conditions' => $additionalConditions,
	    'limit' => $this->pageLimit, 
	    'offset' => ($this->pageNum - 1) * $this->pageLimit
	  ));
    $this->elementsInListAmount = $objHotel->count($additionalConditions); //получаем общее кол-во стран;
	  
	  $this->title = $this->pageHead = 'Администрирование гостиниц';
	  $this->addUrl = W_ADMIN . 'hotels/add/';
	  $objViewHotel = new View_Hotel();
	  $objViewAdminBlock = new View_AdminBlock();
	  $this->showHeader();
      $objViewAdminBlock->showHotelsSearchForm(new Hotel());
	    $objViewHotel->showListForAdmin($arrHotels);
     	$this->showPages();
		$this->showFooter();
	}
	
  /**
   * Выводит страницу редактирования гостиницы
   * 
   * @param Hotel $objHotel - объект гостиницы для редактирования
   */
  public function actionEdit(Hotel $objHotel) {
		Service_Debug::setDebug();
		$editId = $objHotel->id;
		$hotelName = View_Hotel::getName($objHotel->tableFields);
  	if (!empty($_POST['basic_hotel_id'])) {
			$basicHotelId = intval($_POST['basic_hotel_id']);
			if ($objHotel->mergeWithOldHotel($basicHotelId)) User_Session::moveTo(W_ADMIN . 'hotels/edit/' . $objHotel->id .  '/', 'Информация совмещена', 1);
			else User_Session::moveTo(W_ADMIN . 'hotels/edit/' . $objHotel->id .  '/', 'Что-то прошло не так');
		}
		
		if (isset($_POST['Hotel'])) {
			$objHotel = new Hotel($_POST['Hotel']);
			if ($objHotel->id != $editId) User_Session::moveTo(View_Base::getLanguageUrl(W_ADMIN) . 'hotels/', Service_Translate::getText('Недопустимое действие'));
			if ($objHotel->save()) User_Session::moveTo(W_ADMIN . 'hotels/', 'Гостиница успешно сохранена', 1);
		}
		
		$objCity = new City($objHotel->getField('ID_city'));
		$arrOldHotels = $objCity->getOldUncopiedHotels();
		$arrDescriptions = $objHotel->getDescriptions();
		$arrDescriptions = Service_ArrayConverter::makeKeyArrayFromMultyArray($arrDescriptions, 'ID_description_type');
  	
  	$objViewHotel = new View_Hotel();
  	
  	$this->pageHead = $this->title = 'Редактирование гостиницы "' . $hotelName . '"';
  	$this->addWysiwygMetas();
  	$this->showHeader();
  	  $objViewHotel->showMergeForm($objHotel, $arrOldHotels);
      $objViewHotel->showEditForm($objHotel, $arrDescriptions);
    $this->showFooter();
  }
}
?>